//增删改查
const CompanyMaterial = require("../models/companyMaterialModel");
const Goods = require("../models/goodsModel");
const mongooes = require("mongoose");
//获取该公司下所有的材料
exports.getAllComMaterial = async (req, res, next) => {
  try {
    const company_id = String(req.user.company_id);
    const comMaterial = await CompanyMaterial.find({ company_id: company_id });
    res.status(200).json({
      status: true,
      message: comMaterial,
    });
  } catch (err) {
    console.log(err);
    res.status(404).json({
      message: err,
    });
  }
};
//创建公司购入的新材料
exports.createComMaterial = async (req, res, next) => {
  try {
    const item = req.body;
    item.company_id = String(req.user.company_id);
    const newComMaterial = await CompanyMaterial.create(item);
    //成功创建
    res.status(201).json({
      status: "success",
      message: newComMaterial,
    });
  } catch (err) {
    res.status(404).json({
      message: err,
    });
  }
};
//批量删除选定的公司材料
exports.deleteSelectedComMaterial = async (req, res, next) => {
  try {
    // console.log("body", req.body);
    idGroup = req.body.idGroup.map((id) => mongooes.Types.ObjectId(id));
    // console.log("--id", idGroup);
    await CompanyMaterial.deleteMany({ _id: { $in: idGroup } });
    res.status(200).json({
      status: true,
      message: "批量删除成功",
    });
  } catch (err) {
    res.status(404).json({
      status: true,
      message: "批量删除失败",
    });
  }
};
//删除公司材料
exports.deleteComMaterial = async (req, res, next) => {
  try {
    const comId = mongooes.Types.ObjectId(req.params.id);
    const comMaterial = await CompanyMaterial.findById(comId);
    if (!comMaterial) {
      return res.status(404).json({
        message: "公司该材料并不存在",
      });
    }
    await comMaterial.remove();
    //只要商品基板或者覆板使用了该材料 则删除该商品
    const deletedGoods = await Goods.find({
      $or: [{ baseplate: comId }, { shroudplate: comId }],
    });

    // console.log("====", deletedGoods);
    await Goods.deleteMany({
      $or: [{ baseplate: comId }, { shroudplate: comId }],
    });

    // console.log("------", result);
    res.status(200).json({
      status: true,
      message: deletedGoods,
    });
  } catch (err) {
    console.log(err);
    res.status(404).json({
      message: err,
    });
  }
};
//更新公司材料
exports.updateComMaterial = async (req, res, next) => {
  try {
    const comMaterial = await CompanyMaterial.findByIdAndUpdate(
      mongooes.Types.ObjectId(req.params.id),
      req.body,
      {
        new: true,
      }
    );
    if (!comMaterial) {
      return res.status(404).json({
        message: "该材料并不存在",
      });
    }

    res.status(200).json({
      status: "success",
      message: comMaterial,
    });
  } catch (err) {
    res.status(404).json({
      err,
    });
  }
};
